<template>
  <div class="page-container">
    <el-form v-show="!fold" inline :model="queryForm" @submit.prevent>
      <template v-for="item in renderOptions" :key="item.fieldProperty">
        <el-form-item v-if="item.onSearchCol === 1" :label="item.displayName">
          <el-input
            v-if="item.formType === 10 && item.searchCondition !== 'between'"
            v-model="queryForm.query[item.fieldProperty]"
            clearable
            placeholder="请输入"
            style="width: 150px"
          />
          <template
            v-if="item.formType === 10 && item.searchCondition === 'between'"
          >
            <el-input
              v-model="queryForm.query[item.fieldProperty]"
              clearable
              placeholder="请输入"
              style="width: 150px"
            />
            &nbsp; - &nbsp;
            <el-input
              v-model="queryForm.query[item.fieldPropertyEnd]"
              clearable
              placeholder="请输入"
              style="width: 150px"
            />
          </template>
          <el-input
            v-if="item.formType === 12 && item.searchCondition !== 'between'"
            v-model="queryForm.query[item.fieldProperty]"
            clearable
            :controls="false"
            placeholder="请输入"
          />
          <template
            v-if="item.formType === 12 && item.searchCondition === 'between'"
          >
            <el-input-number
              v-model="queryForm.query[item.fieldProperty]"
              clearable
              :controls="false"
              placeholder="请输入"
              style="width: 150px"
            />
            &nbsp; - &nbsp;
            <el-input-number
              v-model="queryForm.query[item.fieldPropertyEnd]"
              clearable
              :controls="false"
              placeholder="请输入"
              style="width: 150px"
            />
          </template>
          <el-date-picker
            v-if="item.formType === 20"
            v-model="queryForm.query[item.fieldProperty]"
            type="datetimerange"
            clearable
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
          <el-select
            v-if="item.formType === 40"
            v-model="queryForm.query[item.fieldProperty]"
            filterable
            clearable
            placeholder="请选择"
            style="width: 150px"
          >
            <el-option
              v-for="option in renderConfigMap[item.fieldProperty].data"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
          <el-tree-select
            v-if="item.formType === 42"
            ref="treeSelectRef"
            v-model="queryForm.query[item.fieldProperty]"
            :data="renderConfigMap[item.fieldProperty].data"
            check-strictly
            clearable
            style="width: 150px"
            :render-after-expand="false"
          />
        </el-form-item>
      </template>
    </el-form>
    <div class="toolbar">
      <div class="operate-container">
        <el-input
          v-model.trim="queryForm.query.keywords"
          placeholder="请输入关键字搜索"
        >
          <template #append>
            <el-button :icon="Search" @click="queryData" />
          </template>
        </el-input>
        <el-button
          :icon="Plus"
          type="primary"
          plain
          class="operate-btn"
          @click="handleAddEdit($event)"
        >
          新增
        </el-button>
        <el-button
          v-permissions="{
            role: ['ROOT'],
            permission: ['sys:assetinfo:delete'],
          }"
          :icon="Delete"
          type="danger"
          plain
          class="operate-btn"
          @click="handleDelete($event)"
        >
          删除
        </el-button>
      </div>
      <div class="config">
        <el-button text type="primary" @click="handleFold">
          <span v-if="fold">展开</span>
          <span v-else>收起</span>
          <vab-icon
            class="vab-dropdown"
            :class="{ 'vab-dropdown-active': fold }"
            icon="arrow-up-s-line"
          />
        </el-button>
        <el-tooltip effect="dark" content="自定义查询配置" placement="top">
          <font-awesome-icon
            icon="fa-regular fa-flag"
            style="cursor: pointer; color: #ff892a"
            @click="handleConfigSettings"
          />
        </el-tooltip>
      </div>
    </div>
    <el-table
      ref="multipleTableRef"
      v-loading="listLoading"
      border
      :data="list"
      :row-class-name="rowClass"
      height="65vh"
      @row-click="toggleSelection"
      @cell-dblclick="dblclick"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" fixed />
      <el-table-column
        type="index"
        width="60"
        header-align="center"
        align="center"
        label="序号"
        fixed
      />
      <template v-for="column in renderOptions" :key="column.fieldProperty">
        <el-table-column
          v-if="column.onDataCol === 1"
          :label="column.displayName"
          :prop="column.fieldProperty"
          :width="column.width ? column.width : 'auto'"
          show-overflow-tooltip
          align="center"
        />
      </template>
      <el-table-column
        label="操作"
        width="100"
        header-align="center"
        fixed="right"
      >
        <template #default="scope">
          <el-tooltip effect="dark" content="分配" placement="top">
            <el-button
              color="#6774DF"
              :icon="Switch"
              @click="handleAssign(scope.row, 'allocation')"
            />
          </el-tooltip>
          <el-tooltip effect="dark" content="报备" placement="top">
            <el-button
              type="warning"
              :icon="DocumentChecked"
              @click="handleAssign(scope.row, 'report')"
            />
          </el-tooltip>
          <el-dropdown style="height: 23px; margin-left: 4px">
            <span class="el-dropdown-link">
              <el-button type="primary">
                <el-icon>
                  <More />
                </el-icon>
              </el-button>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                  v-permissions="{
                    role: ['ROOT'],
                    permission: ['sys:assetinfo:change'],
                  }"
                  @click="handleAssign(scope.row, 'damage')"
                >
                  <span
                    class="iconfont icon-a-JAZP_icon-sunhuai1x"
                    style="margin-right: 6px; font-size: 12px"
                  ></span>
                  报损
                </el-dropdown-item>
                <el-dropdown-item
                  v-permissions="{
                    role: ['ROOT'],
                    permission: ['sys:assetinfo:edit'],
                  }"
                  @click="handleAddEdit(scope.row)"
                >
                  <span
                    class="iconfont icon-bianji"
                    style="margin-right: 6px; font-size: 12px"
                  ></span>
                  编辑
                </el-dropdown-item>
                <el-dropdown-item
                  v-permissions="{
                    role: ['ROOT'],
                    permission: ['sys:assetinfo:delete'],
                  }"
                  @click="handleDelete(scope.row)"
                >
                  <span
                    class="iconfont icon-a-JAZP_icon-shanchu1x"
                    style="margin-right: 6px; font-size: 12px"
                  ></span>
                  删除
                </el-dropdown-item>
                <el-dropdown-item
                  v-permissions="{
                    role: ['ROOT'],
                    permission: ['sys:assetinfo:change'],
                  }"
                  @click="handleDetail(scope.row)"
                >
                  <span
                    class="iconfont icon-a-JAZP_icon-mingxi1x"
                    style="margin-right: 6px; font-size: 12px"
                  ></span>
                  详情
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty class="vab-data-empty" description="暂无数据" />
      </template>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNum"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <user-field-config-dialog
      v-if="dialogVisible"
      v-model:visible="dialogVisible"
      :type-code="queryForm.typeCode"
      :render-options="renderOptions"
      @save="handleConfigDialogSave"
    />
    <custom-field-edit-form-dialog
      ref="editFormRef"
      :module-code="queryForm.typeCode"
      :request-url="associateModuleUrl"
      :render-options="renderOptions"
      :render-data="renderConfigMap"
      @fetch-data="fetchData"
    />
    <edit ref="editRef" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import {
    doDelete,
    doAssetInfo,
    fetchAssetInfoList,
  } from '@/api/assetManagement'
  import request from '@/utils/request'
  import { fetchFieldCfgList } from '@/api/dictConfig'
  import {
    Delete,
    Plus,
    Search,
    Edit,
    Message,
    Document,
    More,
    Switch,
    DocumentChecked,
  } from '@element-plus/icons-vue'
  import { useAclStore } from '@/store/modules/acl'
  export default defineComponent({
    name: 'AssetManagementList',
    components: {
      UserFieldConfigDialog: defineAsyncComponent(() =>
        import('@/components/common/UserFieldConfigDialog')
      ),
      CustomFieldEditFormDialog: defineAsyncComponent(() =>
        import('./CustomFieldEditFormDialog')
      ),
      Edit: defineAsyncComponent(() => import('./components/edit')),
    },
    setup() {
      const router = useRouter()
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')
      const aclStore = useAclStore()
      const { role, permission } = storeToRefs(aclStore)
      const state = reactive({
        fold: true,
        associateModuleUrl: '',
        treeSelectRef: null,
        editFormRef: null,
        renderConfigMap: {}, // 配置项map
        renderOptions: [], // 配置项list
        dialogVisible: false,
        editRef: null,
        multipleTableRef: null,
        list: [],
        DictList: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        queryForm: {
          query: {},
          typeCode: 'assetinfo',
          pageNum: 1,
          pageSize: 20,
        },
        selectRow: [], // 选中的行
        selectRows: [], // 选中的数据
      })
      watch(
        () => state.selectRows,
        (val) => {
          state.selectRow = []
          if (val.length > 0) {
            state.selectRows.forEach((item) => {
              state.selectRow.push(state.list.indexOf(item))
            })
          }
        },
        {
          deep: true,
        }
      )

      //勾选数据行的 Checkbox 时触发的事件
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      const rowClass = ({ row, rowIndex }) => {
        if (state.selectRow.includes(rowIndex)) {
          return 'slecleRowColor'
        }
      }
      //点击行
      const toggleSelection = (rows) => {
        if (rows) {
          state.multipleTableRef &&
            state.multipleTableRef.toggleRowSelection(rows, undefined)
        } else {
          state.multipleTableRef.clearSelection()
        }
      }

      const fetchDetail = (id) => {
        return request({
          url: `${state.associateModuleUrl}/detail?id=${id}`,
          method: 'get',
        })
      }

      // 双击跳转详情
      const dblclick = (rows) => {
        handleDetail(rows)
      }

      // 选中的信息
      const handleSelectionChange = (val) => {
        state.selectRows = val
      }

      const handleFold = () => {
        state.fold = !state.fold
      }

      const handleAssign = async (row, currentStatus) => {
        try {
          const { data, code } = await doAssetInfo(row.id)
          if (code === '1') {
            data.deptId = data.treePath
            state.editRef.showEdit(data, currentStatus)
          } else {
            $baseMessage(msg, 'error', 'vab-hey-message-error')
          }
        } catch (e) {
          console.log(e)
        }
      }
      const handleAddEdit = async (row) => {
        if (row.id) {
          try {
            const { data } = await fetchDetail(row.id)
            state.editFormRef.showEdit(data)
          } catch (e) {
            console.log(e)
          }
        } else {
          state.editFormRef.showEdit()
        }
      }
      const handleDelete = (row) => {
        if (row.id) {
          try {
            $baseConfirm('你确定要删除当前项吗', '提示', async () => {
              const { msg, code } = await doDelete({ ids: [row.id] })
              if (code === '1') {
                $baseMessage(msg, 'success', 'vab-hey-message-success')
                await fetchData()
              } else {
                $baseMessage(msg, 'error', 'vab-hey-message-error')
              }
            })
          } catch (e) {
            console.log(e)
          }
        } else {
          if (state.selectRows.length > 0) {
            try {
              const ids = state.selectRows.map((item) => item.id).join(',')
              $baseConfirm('你确定要删除选中项吗', '提示', async () => {
                const { msg } = await doDelete({ ids: [ids] })
                $baseMessage(msg, 'success', 'vab-hey-message-success')
                await fetchData()
              })
            } catch (e) {
              console.log(e)
            }
          } else {
            $baseMessage('未选中任何行', 'error', 'vab-hey-message-error')
          }
        }
      }
      const handleDetail = (row) => {
        router.push(
          `/asset/assetManagementDetail?id=${row.id}&typeCode=${state.queryForm.typeCode}`
        )
      }
      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData()
      }
      const handleCurrentChange = (val) => {
        state.queryForm.pageNum = val
        fetchData()
      }
      const queryData = () => {
        state.queryForm.pageNum = 1
        fetchData()
      }
      const fetchData = async () => {
        try {
          const params = JSON.parse(JSON.stringify(state.queryForm))
          for (const key in params.query) {
            const data = params.query[key]
            if (!data) {
              delete params.query[key]
              continue
            }
            if (
              Array.isArray(data) &&
              data.length &&
              state.renderConfigMap[key].formType === 20
            ) {
              params.query[key] = {
                left: data[0],
                right: data[1],
              }
            }
            if (key.indexOf('__end') > -1) {
              const originKey = key.split('__')[0]
              params.query[originKey] = {
                left: params.query[originKey],
                right: data,
              }
              delete params.query[key]
            }
          }
          state.listLoading = true
          const { data } = await fetchAssetInfoList(params)
          state.list = data.list
          state.total = data.total
          state.listLoading = false
        } catch (e) {
          console.error(e)
        }
      }

      const handleConfigSettings = () => {
        state.dialogVisible = true
      }

      const handleConfigDialogSave = () => {
        initRenderConfig()
      }

      const requestDictData = (item) => {
        return request({
          url: `/${item.associateModuleCode}/api/v1/${item.associateTypeCode}/listOptions`,
          method: 'post',
          data: {
            typeCode: item.formCode,
          },
        })
      }
      const getRemoteDictData = async (item) => {
        const { data } = await requestDictData(item)
        item.data = data || []
      }

      const requestSelectData = (item) => {
        return request({
          url: `/${item.associateModuleCode}/api/v1/${item.associateTypeCode}/listOptions`,
          method: 'post',
          data: {
            property: item.formCode,
            keywords: '',
          },
        })
      }

      const getRemoteSelectData = async (item) => {
        const { data } = await requestSelectData(item)
        state.renderConfigMap[item.fieldProperty].data = data || []
      }

      const initRenderConfig = async () => {
        try {
          const { data } = await fetchFieldCfgList({
            typeCode: state.queryForm.typeCode,
          })
          if (data && data.length) {
            state.renderOptions = data || []
            data.map((config) => {
              if (!state.associateModuleUrl) {
                state.associateModuleUrl = `/${config.moduleCode}/api/v1/${config.typeCode}`
              }
              if (
                config.formType === 40 &&
                (config.onFormCol === 1 || config.onSearchCol === 1)
              ) {
                // 单选字典下拉
                getRemoteDictData(config)
              }
              if (
                config.formType === 42 &&
                (config.onFormCol === 1 || config.onSearchCol === 1)
              ) {
                getRemoteSelectData(config)
              }
              if (
                (config.formType === 10 || config.formType === 12) &&
                config.searchCondition === 'between'
              ) {
                config['fieldPropertyEnd'] = `${config.fieldProperty}__end`
              }
              state.renderConfigMap[config.fieldProperty] = config
            })
          }
        } catch (e) {
          console.error(e)
        }
      }

      onMounted(() => {
        initRenderConfig()
        fetchData()
      })

      return {
        ...toRefs(state),
        handleDelete,
        handleSizeChange,
        handleCurrentChange,
        queryData,
        fetchData,
        handleDetail,
        handleAddEdit,
        handleAssign,
        handleConfigDialogSave,
        rowClass,
        handleSelectionChange,
        handleConfigSettings,
        toggleSelection,
        dblclick,
        handleFold,
        Delete,
        Plus,
        Search,
        DocumentChecked,
        Switch,
        Edit,
        Message,
        More,
        Document,
        role,
        permission,
      }
    },
  })
</script>

<style scoped>
  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 4px;
  }
  .toolbar .operate-container {
    display: flex;
    position: relative;
  }
  .toolbar .operate-container .operate-btn {
    font-size: 12px;
  }
  :deep() .operate-container .el-button + .el-button {
    margin-left: 8px;
  }
  :deep() .toolbar .operate-container .el-input {
    margin-right: 8px;
  }
  :deep() .toolbar .operate-container .el-input-group__append .el-button {
    background-color: #1990ff;
  }
  :deep()
    .toolbar
    .operate-container
    .el-input-group__append
    .el-button
    .el-icon {
    color: #ffffff;
  }

  .el-dropdown-link {
    display: flex;
    align-items: center;
    color: #1890ff;
    cursor: pointer;
  }

  :deep() .el-table .slecleRowColor {
    background: #eaf4ff !important;
  }

  :deep() .el-table tbody tr:hover > td {
    background-color: #eaf4ff !important;
  }

  :deep() {
    .cell .el-button {
      width: 22px;
      height: 22px;
      padding: 8px 10px;
    }
  }
  .page-container :deep() .el-form--inline .el-form-item {
    margin-right: 16px;
  }
  .page-container :deep() .cell .el-button + .el-button {
    margin-left: 4px;
  }
</style>
